//
//  ECUIVC_Pay.m
//  Edu_iOS2018
//
//  Created by yanyan on 2018/1/20.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECUIVC_Pay.h"
#import "UIView_Helper.h"
#import "CYUIView_base.h"
#import "ECUIVC_OrderDetail.h"
#import "ECCourseOrderModel.h"
#import "ECData_Format.h"
#import "ECUIView_PayFooter.h"
#import "UIView+BorderLine.h"
#import "ECUIVC_Cash.h"
#import "ECData_Json.h"
@interface ECUIView_PayHeader:CYUIView_base
@property(nonatomic,strong)UIImageView *courseImageView;//课程缩略图
@property(nonatomic,strong)UILabel *courseNameLabel;//课程名字
@property(nonatomic,strong)UILabel *priceLabel;//课程价格
@end
@implementation  ECUIView_PayHeader
- (void)addSubviews
{
    [super addSubviews];
    _courseImageView = [UIView_Helper yImageView];
    _courseImageView.contentMode = UIViewContentModeScaleToFill;
    self.courseImageView.layer.cornerRadius = kCourseImageCornerRadius;
    self.courseImageView.layer.masksToBounds = YES;
    [self addSubview:_courseImageView];
    
    _courseNameLabel = [UIView_Helper yLabel];
    _courseNameLabel.numberOfLines = 3;
    _courseNameLabel.font = [UIFont systemFontOfSize:13*kPercentage];
    _courseNameLabel.textColor = [UIColor colorWithHexString:@"#000000"];
    [self addSubview:_courseNameLabel];
    _priceLabel = [UIView_Helper yLabel];
    _priceLabel.font = [UIFont systemFontOfSize:14];
    _priceLabel.textColor = [UIColor colorWithHexString:@"#ef4023"];
    [self addSubview:_priceLabel];
    WeakSelf(weakSelf);
    CGFloat padding = kProportion_Width(36);
    [self.courseImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(padding));
//        make.top.equalTo(self.mas_top).offset(padding*2);
        make.width.equalTo(@(kProportion_Width(320)));
        make.height.equalTo(weakSelf.courseImageView.mas_width).multipliedBy(0.5);
        make.centerY.equalTo(weakSelf);
        
    }];
    [self.courseNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.courseImageView.mas_top);
        make.left.equalTo(weakSelf.courseImageView.mas_right).offset(padding);
        make.right.equalTo(weakSelf).offset(-padding);
        make.height.greaterThanOrEqualTo(@(30));
    }];
   
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.greaterThanOrEqualTo(weakSelf.courseNameLabel.mas_bottom);
        make.left.equalTo(weakSelf.courseNameLabel);
        make.bottom.equalTo(weakSelf.courseImageView);
        make.right.equalTo(weakSelf.courseNameLabel);
    }];
}
@end
@interface ECUIVC_Pay ()<UITableViewDelegate,UITableViewDataSource>
{
    ECUIVC_Cash *uivc_cash;
}
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)ECUIView_PayHeader *headerView;
@property(nonatomic,strong)ECUIView_PayFooter *footerView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation ECUIVC_Pay

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"结算中心";
    [self.bottomView addSubview:self.headerView];
    [self.view addSubview:self.bottomView];
    self.tableView.tableHeaderView = self.bottomView;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.footerView];
    WeakSelf(weakSelf);
    
    self.footerView.block_selected = ^(id obj) {
        // 生成订单
        [weakSelf action_createOrder:obj];
    };
    if (self.isViewLoaded && self.object) {
        [self setObject:self.object];
    }
   
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 160)];
        _bottomView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"coursepay_bgheader"]];
        imageView.frame = CGRectMake(0, 0, kScreenWidth, kScreenWidth*0.244);
        [_bottomView inBorderForColor:[UIColor colorWithHex:0xf5f5f5] borderWidth:10 borderType:UIBorderSideTypeBottom];
        [_bottomView addSubview:imageView];
    }
    return _bottomView;
}
- (ECUIView_PayFooter *)footerView
{
    if (!_footerView) {
        _footerView = [[ECUIView_PayFooter alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame) - kNavHeight - TABBAR_FOOTER_HEIGHT, kScreenWidth, TABBAR_FOOTER_HEIGHT)];
        [_footerView borderForColor:[UIColor colorWithHexString:@"#c1c1c1"] borderWidth:0.5 borderType:UIBorderSideTypeTop];
//        _footerView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        
    }
   
    return _footerView;
}

-(ECUIView_PayHeader *)headerView
{
    if (!_headerView) {
        
        _headerView = [[ECUIView_PayHeader alloc]initWithFrame:CGRectMake(15, 20, kScreenWidth-30, 120)];
        _headerView.backgroundColor = [UIColor whiteColor];
        _headerView.layer.cornerRadius = 3;
        _headerView.layer.borderWidth = 0.5;
        _headerView.layer.borderColor = [[UIColor colorWithHexString:@"#c1c1c1"] CGColor];
        _headerView.layer.masksToBounds = YES;
        
    }
    return _headerView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, CGRectGetHeight(self.view.frame) - kNavHeight- TABBAR_FOOTER_HEIGHT - 100) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.estimatedRowHeight = 45;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerClass:[ECUITVCell_OrderDetail1 class] forCellReuseIdentifier:@"cell"];
    }
    return _tableView;
}
- (void)setObject:(id)object
{
    [super setObject:object];
    if (!self.isViewLoaded) {
        return;
    }
    
    CourseModel *mo = object;
    self.dataSource = [ECData_Format arrayForOrderPayCenter:mo];
    [self.headerView.courseImageView sd_setImageWithURL:[NSURL URLWithString:mo.pictureUrl] placeholderImage:nil];
    self.headerView.courseNameLabel.text = mo.title;
    self.headerView.priceLabel.attributedText = [ECFormatHelper attributedStringForPromotionPrice:mo.price decimal:2 smallFontSize:9 * kPercentage];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.footerView.object = mo;
        [self.tableView reloadData];
    });
    
}

- (void)action_createOrder:(id)sender
{
    DLog(@"生成订单");
    //请求成功 才进入这个页面，否则提示生成订单错误。
    
    WeakSelf(weakSelf);
    CourseModel *mo = self.object;
    
    [HWHttpTool requestWithMethod:@"POST" url:URL_OrderSnWithCourceId(mo.modelId)  params:@{@"shouldPayMoney":mo.price} headers:@{URL_SERVER_HEADER_USERTOKEN_KEY:[UserInfoManager shareUser].token} success:^(id json) {
        id data = [json valueForKey:@"data"];
        if ([data valueForKey:@"sn"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf showOrderCashVC:data];

            });
        }
    } failure:^(NSError *error) {
        if ([ECData_Json tokenFailureForRequestError:error]) {
            DLog(@"失效");
        }
    }];

    
    
}
-(void)showOrderCashVC:(id)data
{
    CourseModel *mo_cource = self.object;
    ECCourseOrderModel *mo = [[ECCourseOrderModel alloc]init];
    mo.orderSN = [data valueForKey:@"sn"];
    mo.totalPrice = mo_cource.price;
    mo.orderId = [data valueForKey:@"id"];
    uivc_cash = [[ECUIVC_Cash alloc]init];
    uivc_cash.object = mo;
    [self.navigationController pushViewController:uivc_cash animated:YES];
}
#pragma mark - delegate -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ECUITVCell_OrderDetail1 *cell =(ECUITVCell_OrderDetail1 *) [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.object = [self.dataSource objectAtIndex:indexPath.row];
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        cell.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        cell.layoutMargins = UIEdgeInsetsZero;
    }
    
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        cell.preservesSuperviewLayoutMargins = false;
    }
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
